import { useState, useEffect, useRef } from 'react';
import { Button, Space, Spin, List, Card, Input, message as m } from 'antd';
import { Table, Modal } from 'com';
import menuStore from 'store/menu';
import { SearchAuditAttendances, GetAuditFlow, Audit } from 'api/teacher_attendance_audit';
import { confirm } from '@/utils/common';
import dayjs from 'dayjs';

/**
 * 格式化字符串
 */
const formatString = 'YYYY-MM-DD HH:mm:ss';

/**
 * 处理课程时间
 * @param {*} param0 
 * @param {*} isFrom 
 * @returns 
 */
const handleCourseTime = ({ ffrom_date, fend_date, efrom_date, eend_date }, isFrom = true) => ffrom_date && `${dayjs(isFrom ? ffrom_date : efrom_date).format(formatString)} 至 ${dayjs(isFrom ? fend_date : eend_date).format(formatString)}`

export default () => {
    /**
   * 考勤列表
   */
    const [list, setList] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 获取审批流的loading
     */
    const [flowLoading, setFlowLoading] = useState(false);
    /**
     * 审批loading
     */
    const [auditLoading, setAuditLoading] = useState(false);
    /**
     * 是否显示可输入文本框
     */
    const [showText, setShowText] = useState(false);
    /**
     * 审批状态
     */
    const [auditStatus, setAuditStatus] = useState(0);
    /**
     * 输入的消息
     */
    const [message, setMessage] = useState('');
    /**
     * 流
     */
    const [flow, setFlow] = useState({});
    /**
     * 审批流
     */
    const [flows, setFlows] = useState([]);
    /**
     * modal
     */
    const modal = useRef();
    /**
     * 列
     */
    const cols = [
        {
            title: '申请人',
            dataIndex: 'teacher_name',
            align: 'center'
        },
        {
            title: '考勤类型',
            dataIndex: 'attendance_name',
            align: "center"
        },
        {
            title: '开始时间',
            dataIndex: 'from_date',
            align: 'center',
            render: text => text && dayjs(text).format(formatString),
        },
        {
            title: '结束时间',
            dataIndex: 'end_date',
            align: 'center',
            render: text => text && dayjs(text).format(formatString),
        },
        {
            title: '我的课程',
            align: 'center',
            render: (text, row) => handleCourseTime(row)
        },
        {
            title: '调换课程',
            align: 'center',
            render: (text, row) => handleCourseTime(row, false)
        },
        {
            title: '消息',
            dataIndex: 'message'
        },
        {
            title: '状态',
            dataIndex: 'status_name',
            align: 'center'
        },
        {
            title: '操作',
            align: 'center',
            width: 150,
            render: (text, row) => <Space>
                {menuStore.auth('updateRole') && <Button type="link" size="small" onClick={() => open({ ...row })}>审批</Button>}
            </Space>
        }
    ]

    /**
     * 打开审批窗体
     * @param {*} row 
     */
    const open = async (row) => {
        setFlow(row);
        try {
            modal.current.show();
            setFlowLoading(true);
            const list = await GetAuditFlow(row.id);
            setFlows(list);
        } catch (error) { }
        setFlowLoading(false);
    }

    /**
     * 获取列表
     */
    const getList = async () => {
        try {
            setLoading(true);
            const list = await SearchAuditAttendances();
            setList(list);
        } catch (error) { }
        setLoading(false);
    }

    useEffect(() => {
        getList();
    }, []);

    /**
     * 显示输入框
     */
    const show = status => {
        setAuditStatus(status);
        setShowText(true);
        if (status !== auditStatus) {
            setMessage('');
        }
    }

    /**
     * 审批
     */
    const audit = async () => {
        if (!message?.trim()) {
            return m.warning('审批消息不能为空');
        }
        try {
            await confirm(`您确定要【${auditStatus === 38 ? '拒绝' : auditStatus === 37 ? '通过' : '退回'}】吗？`);
            setAuditLoading(true);
            await Audit({ id: flow.id, status_id: auditStatus, message });
            cancel();
            getList();
        } catch (error) { }
        setAuditLoading(false);
    }

    /**
     * 取消
     */
    const cancel = () => {
        modal.current.hide();
        setMessage('');
        setShowText(false);
    }

    return <div>
        <h3>审批考勤</h3>
        <hr />
        {menuStore.auth('roleList') && <Table cols={cols} data={list} loading={loading} />}
        <Modal bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }} title="审批考勤" ref={modal} footer={<Space>
            <Button onClick={cancel}>取消</Button>
            {
                showText ? <>
                    <Button type="primary" onClick={() => setShowText(false)}>隐藏</Button>
                    <Button type="primary" loading={auditLoading} onClick={audit}>确定</Button>
                </> : <>
                    <Button type="primary" onClick={() => show(38)}>拒绝</Button>
                    <Button type="primary" onClick={() => show(39)}>退回</Button>
                    <Button type="primary" onClick={() => show(37)}>通过</Button>
                </>
            }
        </Space>}>
            <Spin spinning={flowLoading}>
                <List bordered dataSource={[
                    `申请人：${flow.teacher_name}`,
                    `考勤类型：${flow.attendance_name}`,
                    ...(flow.from_date ? [`时间：${dayjs(flow.from_date).format(formatString)} 至 ${dayjs(flow.end_date).format(formatString)}`] : [`申请人课程：${handleCourseTime(flow)}`, `要调换的课程：${handleCourseTime(flow, false)}`]),
                    `消息：${flow.message}`
                ]} renderItem={(item) => <List.Item>{item}</List.Item>}
                ></List>
                <List dataSource={flows} renderItem={({ id, step, status_name, audit_name, date, auditMessage, message }) => <List.Item style={{ padding: "10px 0" }} key={id}>
                    <Card title={`第${step}步`} style={{ width: "100%" }}>
                        <div>状态：{status_name}</div>
                        {date && <>
                            <div>审批人：{audit_name}</div>
                            <div>审批日期：{dayjs(date).format(formatString)}</div>
                        </>}
                        {message && <div>申请人消息：{message}</div>}
                        {date && <div>审批消息：{auditMessage}</div>}
                    </Card>
                </List.Item>} />
                <div style={{ display: showText ? '' : 'none' }}>
                    <h3>审批消息：</h3>
                    <Input.TextArea value={message} onChange={e => setMessage(e.target.value)}></Input.TextArea>
                </div>
            </Spin>
        </Modal>
    </div >
}